package tickets2;

public class SaleTicket implements Runnable {
	private Integer tickets = 100;

	int i = 0;
	@Override
	public void run() {
		while (true) {
			if (i%2 ==0) {
				sale();
			}else {
				synchronized (this) {
					if (tickets > 0) {
						System.out.println(Thread.currentThread().getName() + " 正在卖第 " + tickets + " 张票");
						tickets--;
					} else {
						System.out.println("票已经卖完");
						break;
					}
				}
			}
			i++;
		}
	}

	private synchronized void sale() {
		while (true) {
			if (tickets > 0) {
				System.out.println(Thread.currentThread().getName() + " 正在卖第 " + tickets + " 张票");
				tickets--;
			} else {
				System.out.println("票已经卖完");
				break;
			}
		}
	}

}
